package devicedbgui;
import devicedbgui.data.Device;
import devicedbgui.data.DeviceDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.filechooser.FileFilter;



/** Displays all devices stored in database */
public class DevicePanel extends javax.swing.JPanel {
    /** Reference to GUI class for accessing its variables */
    public GUI gui;
    Hashtable<Integer, Device> htDevice = new Hashtable<Integer, Device>();
    /** Constructor creates all components belonging to panel     */
    public DevicePanel(GUI gui) {
        initComponents();
        this.gui = gui;
        //this.tableDevice.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ((DefaultTableModel)this.tableDevice.getModel()).getDataVector().clear();
    }
     /** Displays all information in Jtable */ 
    public void fillAllRecords()
    {
        DeviceDAO dd = new DeviceDAO(gui.connection);
        try {
            ArrayList<Device> allRecords = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tableDevice.getModel();
            model.getDataVector().clear();
            int index = 0;
            htDevice.clear();                    
            for (Device item : allRecords){
                htDevice.put(new Integer(index++), item);                
                model.addRow(new Object[]{item.record, item.MAC, item.serial, item.name, item.type});
            }
           
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        
    }
     /** Displays all results fitting search criteria      */
    public void fillResult(ArrayList<Device> result)
    {       
        try {            
            DefaultTableModel model = (DefaultTableModel)tableDevice.getModel();
            model.getDataVector().clear();
            int index = 0;
            htDevice.clear();                    
            for (Device item : result){
                htDevice.put(new Integer(index++), item);                
                model.addRow(new Object[]{item.record, item.MAC, item.serial, item.name, item.type});
            }
           
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cbSearchCriteria = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableDevice = new javax.swing.JTable(){    public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tableDevice.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tableDevice.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnAdd = new javax.swing.JButton();
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();
    btnViewTestResults = new javax.swing.JButton();
    btnViewBuilds = new javax.swing.JButton();
    btnViewRepairInfos = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JSeparator();
    jButton1 = new javax.swing.JButton();
    selectTable = new javax.swing.JComboBox();
    jLabel1 = new javax.swing.JLabel();
    btnViewDeviceStats = new javax.swing.JButton();
    btnViewAllDevicesStats = new javax.swing.JButton();
    btnSave = new javax.swing.JButton();

    jLabel2.setText("Search for:");

    txtSearch.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtSearchbtnSearchActionPerformed(evt);
        }
    });

    jLabel3.setText("in:");

    cbSearchCriteria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Record", "MAC", "Serial", "Name", "Type" }));

    btnSearch.setText("Search");
    btnSearch.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSearchActionPerformed(evt);
        }
    });

    tableDevice.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null},
            {null, null, null, null, null}
        },
        new String [] {
            "Record", "MAC", "Serial", "Name", "Type"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tableDevice.setGridColor(new java.awt.Color(204, 204, 255));
    tableDevice.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(tableDevice);

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    btnViewTestResults.setText("View Test Results");
    btnViewTestResults.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewTestResultsActionPerformed(evt);
        }
    });

    btnViewBuilds.setText("View Builds");
    btnViewBuilds.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewBuildsActionPerformed(evt);
        }
    });

    btnViewRepairInfos.setText("View Repair Infos");
    btnViewRepairInfos.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewRepairInfosActionPerformed(evt);
        }
    });

    jSeparator1.setPreferredSize(new java.awt.Dimension(0, 3));
    jSeparator1.setRequestFocusEnabled(false);

    jButton1.setText("Clear");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    selectTable.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "(Select a table)", "Build", "Exe", "MAC", "Repair Info", "Serial", "Test Case", "Test Result" }));
    selectTable.setPrototypeDisplayValue("XXXXXXXXXXX"); // Set a desired width
    selectTable.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String table = selectTable.getSelectedItem().toString();
            showTable(table);
        }
    });

    jLabel1.setText("View Table: ");

    btnViewDeviceStats.setText("View Device Stats");
    btnViewDeviceStats.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewDeviceStatsActionPerformed(evt);
        }
    });

    btnViewAllDevicesStats.setText("View All Devices Stats");
    btnViewAllDevicesStats.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewAllDevicesStatsActionPerformed(evt);
        }
    });

    btnSave.setText("Save");
    btnSave.setMnemonic(KeyEvent.VK_S);
    btnSave.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSaveActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 612, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGap(15, 15, 15))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                            .addContainerGap())))
                .addGroup(layout.createSequentialGroup()
                    .addGap(6, 6, 6)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnViewAllDevicesStats)
                        .addComponent(btnViewDeviceStats)
                        .addComponent(btnViewTestResults, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                        .addComponent(btnViewRepairInfos, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                        .addComponent(btnViewBuilds, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
                    .addContainerGap())))
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(selectTable, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cbSearchCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnSearch)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addContainerGap(55, Short.MAX_VALUE))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnSave, btnViewAllDevicesStats, btnViewBuilds, btnViewDeviceStats, btnViewRepairInfos, btnViewTestResults});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnSearch)
                .addComponent(cbSearchCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3)
                .addComponent(jButton1)
                .addComponent(jLabel1)
                .addComponent(selectTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addGap(13, 13, 13)
                    .addComponent(btnAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnSave)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(1, 1, 1)
                    .addComponent(btnViewBuilds)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewRepairInfos)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewTestResults)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewDeviceStats)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewAllDevicesStats)))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnViewBuilds, btnViewRepairInfos, btnViewTestResults});

    }// </editor-fold>//GEN-END:initComponents
    /** Displays values in database table selected by user      */
    public void showTable(String table) {
        if (gui.connection == null) {
            JOptionPane.showMessageDialog(new JFrame(), "Not Connected to Database!",
                    "Error 1", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try {
           if (table.equalsIgnoreCase("Build")) {
                BuildPanel b = new BuildPanel();
                b.showAllBuilds(gui);
                gui.tab.add(b);
                gui.tab.setSelectedComponent(b);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Build") );
               
            } else if (table.equalsIgnoreCase("Exe")) {
                ExePanel e = new ExePanel();
                e.showAll(gui);
                gui.tab.add(e);
                gui.tab.setSelectedComponent(e);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Exe") );
               
            } else if (table.equalsIgnoreCase("MAC")) {
                MACPanel m = new MACPanel();
                m.showAll(gui);
                gui.tab.add(m);
                gui.tab.setSelectedComponent(m);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("MAC") );
               
            } else if (table.equalsIgnoreCase("Repair Info")) {
                RepairInfoPanel r = new RepairInfoPanel();
                r.showAll(gui);
                gui.tab.add(r);
                gui.tab.setSelectedComponent(r);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Repair Info") );
               
            } else if (table.equalsIgnoreCase("Serial")) {
                SerialPanel s = new SerialPanel();
                s.showAll(gui);
                gui.tab.add(s);
                gui.tab.setSelectedComponent(s);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Serial") );
               
            } else if (table.equalsIgnoreCase("Test Case")) {
                TestCasePanel t = new TestCasePanel();
                t.showAll(gui);
                gui.tab.add(t);
                gui.tab.setSelectedComponent(t);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Test Case") );
               
            } else if (table.equalsIgnoreCase("Test Result")) {
                TestResultPanel tr = new TestResultPanel();
                tr.showAll(gui);
                gui.tab.add(tr);
                gui.tab.setSelectedComponent(tr);
                gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Test Result") );
               
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(new JFrame(), ex.toString());
        }
    }
 /** Calls action for search button */   
private void txtSearchbtnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchbtnSearchActionPerformed
    btnSearchActionPerformed(evt);
}//GEN-LAST:event_txtSearchbtnSearchActionPerformed
/** Logic for search button action */
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
    if (gui.connection == null) {
            return;
        }
    String searchString = txtSearch.getText();
    // search criteria
    String criteria = this.cbSearchCriteria.getSelectedItem().toString();
    ArrayList<Device> searchResults = null;
    DeviceDAO dd = new DeviceDAO((gui.connection));
    try {
        if (criteria.equalsIgnoreCase("Record")) {
                searchResults = dd.searchByRecord(searchString);
            }
        else if (criteria.equalsIgnoreCase("MAC")) {
                searchResults = dd.searchByMAC(searchString);
            }
        else if (criteria.equalsIgnoreCase("Serial")) {
                searchResults = dd.searchBySerial(searchString);
            }
        else if (criteria.equalsIgnoreCase("Name")) {
                searchResults = dd.searchByName(searchString);
            }
        else if (criteria.equalsIgnoreCase("Type")) {
                searchResults = dd.searchByType(searchString);
            }
        
        // fill table
        fillResult(searchResults);
    } catch (Exception ex){
        JOptionPane.showMessageDialog(gui.frame, ex.toString());
    }
}//GEN-LAST:event_btnSearchActionPerformed
/** Adds device to database */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
    if (gui.connection == null) {
            return;
        }
    EditDeviceDlg dlg = new EditDeviceDlg(this, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB) {
            fillAllRecords();
        }
}//GEN-LAST:event_btnAddActionPerformed
/** Edits device information */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
    //DefaultTableModel model = (DefaultTableModel)tableDevice.getModel();
    int selectedIndex = tableDevice.getSelectedRow();
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to Edit");    
        return;
    }
    Device item = htDevice.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to Edit");
        return;
    }
    
    EditDeviceDlg dlg = new EditDeviceDlg(this, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB)
        fillAllRecords();
}//GEN-LAST:event_btnEditActionPerformed
/** Deletes device record from database */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    int[] selected = tableDevice.getSelectedRows();
    
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to Delete");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete this record?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        DeviceDAO dd = new DeviceDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                Device item = htDevice.get(new Integer(selected[i]));   
                dd.delete(item.record);
                htDevice.remove(new Integer(selected[i]));
            }              
            fillAllRecords();
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/** Displays test results associated with selected device */
private void btnViewTestResultsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewTestResultsActionPerformed
    int selectedIndex = tableDevice.getSelectedRow();
    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View Test Results");
        return;
    }
    
    Device item = htDevice.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View Test Results");
        return;
    }
    gui.setDeviceInfo(item.record, item.MAC, item.serial, item.name);
    gui.setDeviceRecord(item.record);
    TestResultPanel t = new TestResultPanel();    
    t.showAllTestResults(gui, item);
    
      
   
   gui.tab.add(t);
    gui.tab.setSelectedComponent(t);
    gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("View Test Results") );
   
}//GEN-LAST:event_btnViewTestResultsActionPerformed
/** Displays builds associated with current device */
private void btnViewBuildsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewBuildsActionPerformed
    int selectedIndex = tableDevice.getSelectedRow();
    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View Builds");
        return;
    }
    
    Device item = htDevice.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View Builds");
        return;
    }
   
   gui.setDeviceInfo(item.record, item.MAC, item.serial, item.name);
       
       
   BuildPanel b=new BuildPanel();
   b.showBuilds(gui, item);
   
   gui.tab.add(b);
   gui.tab.setSelectedComponent(b);
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("View Build") );
  
}//GEN-LAST:event_btnViewBuildsActionPerformed
/** Displays repair information for selected device */
private void btnViewRepairInfosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewRepairInfosActionPerformed
    int selectedIndex = tableDevice.getSelectedRow();
    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View RepairInfos");
        return;
    }
    
    Device item = htDevice.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item to View RepairInfos");
        return;
    }
    gui.setDeviceInfo(item.record, item.MAC, item.serial, item.name);
    RepairInfoPanel r = new RepairInfoPanel();    
    r.showRepairInfos(gui, item);
    

   
   gui.tab.add(r);
   gui.tab.setSelectedComponent(r);
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Repair Info") );
  
}//GEN-LAST:event_btnViewRepairInfosActionPerformed
/** Gives functionality to clear button */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
fillAllRecords();
}//GEN-LAST:event_jButton1ActionPerformed
/** Displays statistics associated with selected device */
private void btnViewDeviceStatsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewDeviceStatsActionPerformed
    int selectedIndex = tableDevice.getSelectedRow();
    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item.");
        return;
    }
    
    Device item = htDevice.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item.");
        return;
    }
     gui.setDeviceInfo(item.record, item.MAC, item.serial, item.name);
    DeviceStatsPanel panel = new DeviceStatsPanel(gui, item.record);    
    gui.tab.add(panel);
    gui.tab.setSelectedComponent(panel);
    gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Device Stats") );
    
}//GEN-LAST:event_btnViewDeviceStatsActionPerformed
/** Displays statistics for all devices in database */
private void btnViewAllDevicesStatsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewAllDevicesStatsActionPerformed
    DeviceStatsPanel panel = new DeviceStatsPanel(gui);    
    gui.tab.add(panel);
    gui.tab.setSelectedComponent(panel);
    gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Device Stats") );
}//GEN-LAST:event_btnViewAllDevicesStatsActionPerformed
/** Saves all device information from database to local computer*/
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed

JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setDialogTitle("Save Device List");
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }
            public String getDescription() {
                return "*.csv";
            }
        });
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
       File file = fileChooser.getSelectedFile();
if (file.getName().indexOf('.')==-1){
    file = new File(file.getAbsolutePath()+".csv");
}  
   try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write("Record,MAC,Serial,Name,Type\r\n");
            for (Device item : htDevice.values()){
                bw.write(String.format("%s,%s,%s,%s,%s\r\n", 
                        new Object[]{item.record, item.MAC, item.serial, 
                        item.name, item.type}));
            }
            bw.flush();
            bw.close();
            JOptionPane.showMessageDialog(gui.frame, "File has been saved successfully");
        }
    catch (Exception e){
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }


}//GEN-LAST:event_btnSaveActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnViewAllDevicesStats;
    private javax.swing.JButton btnViewBuilds;
    private javax.swing.JButton btnViewDeviceStats;
    private javax.swing.JButton btnViewRepairInfos;
    private javax.swing.JButton btnViewTestResults;
    private javax.swing.JComboBox cbSearchCriteria;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox selectTable;
    private javax.swing.JTable tableDevice;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables

}

